package com.inter.controller.newoutside;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.inter.entity.interentity.utils.UtilsInterfacesPackage;
import com.inter.entity.newinterentity.queryorder.request.RequestordersQuery;
import com.inter.entity.newinterentity.queryorder.request.RequestordersQueryDate;
import com.inter.entity.newinterentity.queryorder.request.RequestordersQueryTradeData;
import com.inter.entity.newinterentity.queryorder.response.ResponseordersQuery;
import com.inter.entity.newinterentity.queryorder.response.ResponseordersQueryData;
import com.inter.entity.newinterentity.queryorder.response.ResponseordersQueryRefuelingPackageList;
import com.inter.entity.newinterentity.queryorder.response.ResponseordersQueryTradeData;
import com.inter.entity.newpojo.response.responseBody.QueryOrderResponseBody;
import com.inter.entity.newpojo.response.subResponse.common.PackageOrder;
import com.inter.entity.newpojo.response.subResponse.common.Page;
import com.inter.entity.newpojo.response.subResponse.common.RefuelingPackageList;
import com.inter.insideinterservice.newservice.TrunToQueryorderService;
import com.inter.service.PartnerProductPackageService;
import com.inter.service.PartnerService;
import com.inter.service.SequenceService;
import com.inter.utils.MD5;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 查询订单信息
 *
 * @author lm
 * @date 2018/12/20
 */
@RestController
@Api(description = "查询套餐订单信息")
public class QueryController {
    private static Logger logger = Logger.getLogger(QueryController.class);

    @Autowired
    HttpSession session;
    @Autowired
    SequenceService sequenceService;
    @Autowired
    PartnerService partnerService;
    @Autowired
    PartnerProductPackageService partnerProductPackageService;


    @CrossOrigin
    @RequestMapping(value = "orderQuery", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "查询订单", response = ResponseordersQuery.class)
    public String orderQuery(@ApiParam @RequestBody RequestordersQuery requestordersQuery) {
        // 1，生成流水号
        String connSeqNo = sequenceService.getPackageTaskNo();
        // 2,生成当前时间戳
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String curtime = df.format(new Date());
        //3,定义要回复的内容
        String jsonString;
        UtilsInterfacesPackage utils = new UtilsInterfacesPackage();
        String requestStr = JSON.toJSONString(requestordersQuery);

        if (StringUtils.isBlank(requestStr)) {
            logger.info("请求报文不合法:requestStr为空");
            jsonString = utils.dataWeiKong(connSeqNo, curtime);
            return jsonString;
        } else {
            logger.info("前端请求是：" + requestStr);
            RequestordersQuery requestPackage = JSONArray.parseObject(requestStr, RequestordersQuery.class);
            String requestSign = requestPackage.getSign();
            if (requestPackage.getSign() == null) {
                logger.info("请求报文不合法:sign为空");
                jsonString = utils.dataWeiKong(connSeqNo, curtime);
                return jsonString;
            } else {
                //logger.info("请求的签名是：" + requestSign);
                RequestordersQueryDate requestData = requestPackage.getData();
                if (requestPackage.getData() == null) {
                    logger.info("请求报文不合法:data为空");
                    jsonString = utils.dataWeiKong(connSeqNo, curtime);
                    return jsonString;
                } else {

                    String partnerCode = requestData.getPartnerCode();
                    String secret = partnerService.findSecretByPartnerCode(partnerCode);
                    String ConnSeqNo = requestData.getConnSeqNo();
                    String tradeTime = requestData.getTradeTime();
                    String token = requestData.getToken();
                    String tradeType = requestData.getTradeType();
                    String lang = requestData.getLang();

                    RequestordersQueryTradeData tradeData = requestData.getTradeData();

                    if (StringUtils.isBlank(partnerCode) || StringUtils.isBlank(secret) || StringUtils.isBlank(ConnSeqNo) || StringUtils.isBlank(tradeTime) || StringUtils.isBlank(token) || StringUtils.isBlank(tradeType) || tradeData == null) {
                        logger.info("请求报文不合法:data参数不合法");
                        jsonString = utils.dataWeiKong(connSeqNo, curtime);
                        return jsonString;
                    } else {

                        String deviceId = requestData.getTradeData().getDeviceId();
                        String orderType = requestData.getTradeData().getOrderType();
                        String orderId = requestData.getTradeData().getOrderId();
                        String orderStatus = requestData.getTradeData().getOrderStatus();
                        Integer pageNo = requestData.getTradeData().getPageNo();
                        Integer pageSize = requestData.getTradeData().getPageSize();

                        if (StringUtils.isBlank(deviceId) || StringUtils.isBlank(orderType) || StringUtils.isBlank(orderId) || StringUtils.isBlank(orderStatus) || pageNo == null || pageSize == null) {
                            logger.info("请求报文不合法:查询条件中参数可以为空，不能为null");
                            jsonString = utils.dataWeiKong(connSeqNo, curtime);
                            return jsonString;
                        } else {
                            // 将请求体json转成String
                            String str = JSON.toJSONString(requestData);
                            // 将Str拿去计算签名
                            String sign = utils.calculateSignature(str);
                            //logger.info("计算的签名是：" + sign);
                            if (!requestSign.equalsIgnoreCase(sign)) {
                                logger.info("签名验证失败！");
                                jsonString = utils.publicMessage(ConnSeqNo, partnerCode, tradeTime, token, tradeType);
                                return jsonString;
                            } else {
                                //签名验证通过
                                //2:拿着现在有的数据去北北京查询
                                TrunToQueryorderService trunToQueryorderService = new TrunToQueryorderService();
                                QueryOrderResponseBody responseBody = trunToQueryorderService.queryOrder(partnerCode, deviceId, orderType, orderId, orderStatus, secret, pageNo, pageSize);

                                Page page = null;

                                List<ResponseordersQueryTradeData> tradeDataList = new ArrayList<ResponseordersQueryTradeData>();
                                ResponseordersQueryTradeData tra = null;

                                List<ResponseordersQueryRefuelingPackageList> lists = new ArrayList<ResponseordersQueryRefuelingPackageList>();
                                ResponseordersQueryRefuelingPackageList refueling = null;

                                if (responseBody == null) {

                                    page = new Page();

                                    ResponseordersQueryData data = new ResponseordersQueryData();
                                    data.setConnSeqNo(connSeqNo);
                                    data.setPartnerCode(partnerCode);
                                    data.setToken(token);
                                    data.setTradeType(tradeType);
                                    data.setTradeTime(tradeTime);
                                    data.setTradeRstCode(1003);
                                    data.setTradeRstMessage("The order was not queried;未查询到订单");
                                    data.setTradeData(tradeDataList);
                                    data.setPage(page);

                                    ResponseordersQuery responseQueryorder = new ResponseordersQuery();
                                    responseQueryorder.setData(data);
                                    responseQueryorder.setSign(MD5.calcMD5(JSON.toJSONString(data)));
                                    // 返回给调用者的报文
                                    jsonString = JSON.toJSONString(responseQueryorder);
                                    logger.info("响应报文：" + jsonString);
                                    return jsonString;

                                } else {

                                    if (responseBody.getPackageOrder() == null || responseBody.getPackageOrder().size() <= 0) {

                                        page = new Page();

                                        ResponseordersQueryData data = new ResponseordersQueryData();
                                        data.setConnSeqNo(connSeqNo);
                                        data.setPartnerCode(partnerCode);
                                        data.setToken(token);
                                        data.setTradeType(tradeType);
                                        data.setTradeTime(tradeTime);
                                        data.setTradeRstCode(1003);
                                        data.setTradeRstMessage("The order was not queried;无正常订单返回");
                                        data.setTradeData(tradeDataList);
                                        data.setPage(page);

                                        ResponseordersQuery responseQueryorder = new ResponseordersQuery();
                                        responseQueryorder.setData(data);
                                        responseQueryorder.setSign(MD5.calcMD5(JSON.toJSONString(data)));
                                        // 返回给调用者的报文
                                        jsonString = JSON.toJSONString(responseQueryorder);
                                        logger.info("响应报文：" + jsonString);
                                        return jsonString;


                                    } else {

                                        for (PackageOrder order : responseBody.getPackageOrder()) {

                                            String packageName = order.getPackageName();
                                            String packageNameEN = partnerProductPackageService.queryPackageName(packageName, partnerCode);

                                            //有加油包
                                            if (StringUtils.isNotBlank(order.getIsOrderRefuelingPackage()) && "1".equals(order.getIsOrderRefuelingPackage())) {

                                                if (order.getRefuelingPackageList() != null && order.getRefuelingPackageList().size() > 0) {

                                                    for (RefuelingPackageList re : order.getRefuelingPackageList()) {
                                                        refueling = new ResponseordersQueryRefuelingPackageList();

                                                        refueling.setRefOrderId(re.getRefOrderId());
                                                        refueling.setRefpackageStatus(re.getRefpackageStatus());
                                                        refueling.setRefpackageFlow(re.getRefPackageFlow());
                                                        refueling.setRefpackageOrderDate(re.getRefpackageOrderDate());
                                                        lists.add(refueling);
                                                    }
                                                }

                                            }

                                            tra = new ResponseordersQueryTradeData();
                                            tra.setOrderId(order.getOrderCode());
                                            tra.setDeviceId(order.getDeviceId());
                                            tra.setPackageCode(order.getPackageCode());
                                            tra.setPackageType(order.getPackageType());
                                            tra.setOrderStatus(order.getOrderStatus());
                                            tra.setOrderPeriod(order.getOrderPeriod());
                                            if ("en".equals(lang)) {
                                                tra.setPackageName(packageNameEN);
                                            } else {
                                                tra.setPackageName(order.getPackageName());
                                            }
                                            if (StringUtils.isNotBlank(order.getBuyType())) {
                                                tra.setBuyType(order.getBuyType());
                                            } else {
                                                tra.setBuyType("");
                                            }
                                            if (StringUtils.isNotBlank(order.getFlow())) {
                                                tra.setFlow(order.getFlow());
                                            } else {
                                                tra.setFlow("");
                                            }
                                            if (StringUtils.isNotBlank(order.getUsedFlow())) {
                                                tra.setUsedFlow(order.getUsedFlow());
                                            } else {
                                                tra.setUsedFlow("");
                                            }
                                            if (StringUtils.isNotBlank(order.getFlowUseRate())) {
                                                tra.setFlowUseRate(order.getFlowUseRate());
                                            } else {
                                                tra.setFlowUseRate("");
                                            }
                                            if (StringUtils.isNotBlank(order.getOrderUsedFlow())) {
                                                tra.setOrderUsedFlow(order.getOrderUsedFlow());
                                            } else {
                                                tra.setOrderUsedFlow("");
                                            }
                                            if (StringUtils.isNotBlank(order.getOrderCode())) {
                                                tra.setOrderDate(order.getOrderCode());
                                            } else {
                                                tra.setOrderDate("");
                                            }
                                            if (StringUtils.isNotBlank(order.getActiveDate())) {
                                                tra.setActiveDate(order.getActiveDate());
                                            } else {
                                                tra.setActiveDate("");
                                            }
                                            if (StringUtils.isNotBlank(order.getExpireDate())) {
                                                tra.setExpireDate(order.getExpireDate());
                                            } else {
                                                tra.setExpireDate("");
                                            }
                                            if (StringUtils.isNotBlank(order.getIsOrderRefuelingPackage())) {
                                                tra.setIsOrderRefueling(order.getIsOrderRefuelingPackage());
                                            } else {
                                                tra.setIsOrderRefueling("");
                                            }
                                            tra.setRefuelingPackageList(lists);
                                            tradeDataList.add(tra);

                                        }

                                    }

                                    //在这边获取page信息
                                    page = new Page();
                                    page.setCurrentPageNo(responseBody.getPage().getCurrentPageNo());
                                    page.setPageSize(responseBody.getPage().getPageSize());
                                    page.setTotalCount(responseBody.getPage().getTotalCount());
                                    page.setTotalPages(responseBody.getPage().getTotalPages());

                                }

                                //在外面准备data
                                ResponseordersQueryData data = new ResponseordersQueryData();
                                data.setConnSeqNo(connSeqNo);
                                data.setPartnerCode(partnerCode);
                                data.setToken(token);
                                data.setTradeType(tradeType);
                                data.setTradeTime(tradeTime);
                                data.setTradeRstCode(1000);
                                data.setTradeRstMessage("success");
                                data.setTradeData(tradeDataList);
                                data.setPage(page);

                                ResponseordersQuery responseQueryorder = new ResponseordersQuery();
                                responseQueryorder.setData(data);
                                responseQueryorder.setSign(MD5.calcMD5(JSON.toJSONString(data)));
                                // 返回给调用者的报文
                                jsonString = JSON.toJSONString(responseQueryorder);
                                logger.info("响应报文：" + jsonString);
                                return jsonString;
                            }
                        }
                    }
                }
            }

        }

    }
}
